package com.wpx.log.core.handler;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.wpx.log.core.LogContext;
import com.wpx.log.core.LogRequestContext;
import com.wpx.log.core.handler.param.ILogParamTypePolicy;
import com.wpx.log.core.module.LogParam;

public class OpParameterLogHandler implements ILogHandler {

	@Override
	public boolean isSync() {
		return true;
	}

	@Override
	public Object handler(LogContext logContext, LogRequestContext logRequestContext, Field logField) {
		List<LogParam> params = new ArrayList<LogParam>();
		HttpServletRequest request = logRequestContext.getHttpServletRequest();
		String contentType = request.getContentType();
		if(contentType == null) {
			return JSON.toJSON(params);
		}
		int indexOf = contentType.indexOf(";");
		if(indexOf != -1) {
			contentType = contentType.substring(0, indexOf);
		}
		
		ILogParamTypePolicy policy = logContext.getLogParamTypePolicy(contentType);
		if(policy != null) {
			policy.parseParam(logContext, logRequestContext, logField,params);
		}else {
			params.add(new LogParam("errMsg", "沒有contentType="+contentType+"对应的参数处理器", LogParam.TYPE_BASE));
		}

		return JSON.toJSON(params);
	}

}
